<template>
  <div class="content-box" v-loading="isLoadIframe">
    <iframe
      class="item"
      :class="{ cover_item: isCoverIframe }"
      :src="src"
      frameborder="0"
      name="content"
      id="content"
      @load="init"
      @error="err"
      seamless
    ></iframe>
  </div>
</template>

<script>
import { mapState } from 'vuex';
import NProgress from 'nprogress';
export default {
  data() {
    return {
      src: undefined,
      isLoadIframe: false, // Iframe是否加载完成
      isCoverIframe: false, // Iframe是否全屏
      isCoverIframeNum: 0, // 全屏计数
    };
  },
  computed: {
    ...mapState(['isCollapse']),
  },
  watch: {
    $route() {
      this.init();
    },
  },
  mounted() {
    window.addEventListener('message', this.receiveMsg);
  },
  methods: {
    // 初始化
    init(e) {
      NProgress.start();
      this.isLoadIframe = true;

      const { path, name, meta } = this.$route;
      const { orgin, pathName } = meta;

      if (this.src === `${orgin}${pathName}`) {
        this.sendMsg2content({ type: 'changeRoute', params: { path, name } });
        this.sendMsg2content({
          type: 'isCollapse',
          params: { collapse: this.isCollapse },
        });
        this.isLoadIframe = false;
        NProgress.done();
      } else {
        this.src = `${orgin}${pathName}`;
      }
    },
    // 收到子窗口消息
    receiveMsg(info) {
      let { data } = info;
      switch (data.type) {
        // iframe覆盖
        case 'setIframeCover':
          this.setIframeCover();
          break;
        // iframe覆盖取消
        case 'cancelIframeCover':
          this.cancelIframeCover();
          break;
        // 弹窗message显示
        case 'showTopMessage':
          this.showTopMessage(data.params);
          break;
        default:
          break;
      }
    },
    // 弹出消息提示
    showTopMessage(options) {
      this.$message(options);
    },
    // 设置Iframe全屏
    setIframeCover() {
      this.isCoverIframe = true;
      this.isCoverIframeNum++;
      console.log('弹窗数：' + this.isCoverIframeNum);
    },
    // 取消Iframe全屏
    cancelIframeCover() {
      this.isCoverIframeNum--;
      console.log('弹窗数：' + this.isCoverIframeNum);
      if (this.isCoverIframeNum <= 0) {
        this.isCoverIframeNum = 0;
        setTimeout(() => {
          this.isCoverIframe = false;
        }, 200);
      }
    },
  },
};
</script>

<style lang="less" scoped>
.content-box {
  flex: 1;
  overflow: hidden;

  .item {
    position: fixed;
    z-index: 1;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 100vw;
    height: 100vh;
    min-width: 1300px;
  }

  .cover_item {
    z-index: 2;
  }
}
</style>
